#pragma once
#include <string>
#include <jsoncpp/json/json.h>

static const std::string sep = "\r\n";
// 添加报头
std::string EnCode(const std::string &jsonStr)
{
    int len = jsonStr.size();
    std::string lenStr = std::to_string(len);
    return lenStr + sep + jsonStr + sep;
}

std::string DeCode(std::string &packageStream)
{
    size_t n = packageStream.find(sep);
    if (n == std::string::npos)
        return "";
    std::string numStr = packageStream.substr(0, n);
    int len = std::stoi(numStr);
    int total = numStr.size() + len + 2 * sep.size();
    if (packageStream.size() < total)
        return "";
    int pos = n + sep.size();
    std::string jsonStr = packageStream.substr(pos, len);
    packageStream.erase(0, total);
    return jsonStr;
}

// 请求
class Request
{
public:
    Request(int x = 1, int y = 1, char oper = '+')
        : _x(x), _y(y), _oper(oper)
    {
    }
    // 序列化：将结构化字段转换成字符串
    void Serialize(std::string &out)
    {
        Json::Value root;
        root["x"] = _x;
        root["y"] = _y;
        root["oper"] = _oper;
        Json::FastWriter writer;
        std::string s = writer.write(root);
        out = s;
    }
    bool Deserialize(std::string &in)
    {
        Json::Value root;
        Json::Reader reader;
        bool res = reader.parse(in, root);
        if (res)
        {
            _x = root["x"].asInt();
            _y = root["y"].asInt();
            _oper = root["oper"].asInt();
            return true;
        }
        return false;
    }
    int RetX()
    {
        return _x;
    }
    int RetY()
    {
        return _y;
    }
    char RetOper()
    {
        return _oper;
    }
    ~Request()
    {
    }

    // private:
    int _x;
    int _y;
    char _oper;
};

// 回应
class Response
{
public:
    Response()
        : _result(2), _code(0), _describe("Calculation successful")
    {
    }
    // 序列化
    void Serialize(std::string &out)
    {
        Json::Value root;
        root["result"] = _result;
        root["code"] = _code;
        root["describe"] = _describe;
        Json::FastWriter writer;
        std::string s = writer.write(root);
        out = s;
    }
    // 反序列化
    bool Deserialize(std::string &in)
    {
        Json::Value root;
        Json::Reader reader;
        bool res = reader.parse(in, root);
        if (res)
        {
            _result = root["result"].asInt();
            _code = root["code"].asInt();
            _describe = root["describe"].asString();
            return true;
        }
        return false;
    }
    ~Response()
    {
    }

    // private:
    int _result;
    int _code;
    std::string _describe;
};